package com.luobd.db.impl;

import com.luobd.db.Column;
import com.luobd.db.MetadataFetcher;
import com.luobd.db.Table;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class HiveMetadataFetcher implements MetadataFetcher {
    private final Connection connection;
    private final String database;

    public HiveMetadataFetcher(Connection connection, String database) {
        this.connection = connection;
        this.database = database;
    }

    @Override
    public List<Table> getTables() throws SQLException {
        List<Table> tables = new ArrayList<>();
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SHOW TABLES IN " + database)) {
            while (rs.next()) {
                Table table = new Table();
                String tableName = rs.getString(1);
                table.setName(tableName);
                table.setComment(getHiveTableComment(tableName));
                table.setColumns(getHiveColumns(tableName));
                tables.add(table);
            }
        }
        return tables;
    }

    // Hive通过DESCRIBE EXTENDED获取元数据
    private String getHiveTableComment(String tableName) throws SQLException {
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("DESCRIBE EXTENDED " + database + "." + tableName)) {
            while (rs.next()) {
                String info = rs.getString(1);
                if (info.startsWith("comment:")) {
                    return info.split("comment:")[1].trim();
                }
            }
        }
        return "";
    }

    private List<Column> getHiveColumns(String tableName) throws SQLException {
        List<Column> columns = new ArrayList<>();
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("DESCRIBE " + database + "." + tableName)) {
            while (rs.next()) {
                String colName = rs.getString(1);
                if (colName.startsWith("#")) continue; // 跳过分区信息

                Column col = new Column();
                col.setName(colName);
                String[] typeInfo = rs.getString(2).split("\\s+");
                col.setType(typeInfo[0]);
                col.setComment(typeInfo.length > 1 ? typeInfo[1] : "");
                columns.add(col);
            }
        }
        return columns;
    }
}
